import React from 'react';
import { Table, Rate } from 'antd';
import styles from './index.less';

export default props => {
    const {
        form: { getFieldDecorator, setFieldsValue },
        data,
        isDetail = false,
        modalTableData
    } = props;

    const copywriting = ['很差', '差', '一般', '好', '很好'];
    const [score, setScore] = React.useState({});
    const [comprehensiveScore, setComprehensiveScore] = React.useState(0);
    const [dataSource, setDataSource] = React.useState(
        modalTableData.map((item, index) => ({ ...item, key: item.id || index }))
    );
    getFieldDecorator('taskScoreRuleDetails', {});
    getFieldDecorator('comprehensiveScore', { initialValue: 0 });
    const onScoreChange = (val, record) => {
        const newScore = { ...score, [record.key]: val };
        setScore(newScore);
        setFieldsValue({
            taskScoreRuleDetails: Object.keys(newScore).map(scoreKey => ({
                ...dataSource.find(item => item.key === Number(scoreKey)),
                score: 1, // 每个星代表1分
                scoreResult: newScore[scoreKey]
            }))
        });
    };

    const showEllipsisText = (text, width) => (
        <div style={{ width }} title={text}>
            <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{text}</div>
        </div>
    );

    const columns = [
        {
            key: 'scoreTarget',
            dataIndex: 'scoreTarget',
            title: '评分指标',
            render: text => showEllipsisText(text, '100px')
        },
        {
            key: 'scoreStandard',
            dataIndex: 'scoreStandard',
            title: '指标说明',
            width: 280,
            render: text => showEllipsisText(text, '280px')
        },
        {
            key: 'scoreResult',
            dataIndex: 'scoreResult',
            title: (
                <>
                    评分星级 <span style={{ color: 'red' }}>*</span>
                </>
            ),
            width: 300,
            render: (text, record) => (
                <Rate
                    tooltips={copywriting}
                    value={score[record.key]}
                    onChange={val => onScoreChange(val, record)}
                    disabled={isDetail}
                />
            )
        }
    ];
    // 详情页初始化数据
    React.useEffect(() => {
        const dimensionList = data.artificialRuleResults || data.taskScoreRuleDetails;
        if (dimensionList) {
            const defaultScore = dimensionList.reduce((prev, curr, index) => {
                const newPrev = { ...prev };
                newPrev[curr.id || index] = curr.scoreResult;
                return newPrev;
            }, {});
            const defaultDataSource = dimensionList.map((item, index) => ({ ...item, key: item.id || index }));
            setScore(defaultScore);
            setDataSource(defaultDataSource);
        }
    }, []);
    React.useEffect(() => {
        let isFinished = true;
        let totalScore = 0;
        for (let i = 0; i < dataSource.length; i += 1) {
            if (!score[dataSource[i].key]) {
                isFinished = false;
                break;
            } else {
                totalScore += score[dataSource[i].key];
            }
        }
        if (isFinished && dataSource.length > 0) {
            const val = (totalScore / dataSource.length).toFixed(1);
            setComprehensiveScore(val);
            setFieldsValue({ comprehensiveScore: Number(val) });
        } else if (comprehensiveScore !== 0) {
            setComprehensiveScore(0);
            setFieldsValue({ comprehensiveScore: 0 });
        }
    }, [score]);
    return (
        <div className={styles.scoreTable}>
            <Table rowKey="key" dataSource={dataSource} columns={columns} pagination={false} scroll={{ x: 500 }} />
            <div className={styles.comprehensiveScore}>
                综合评分：
                <span>
                    {comprehensiveScore || ''}
                    {comprehensiveScore ? '分' : ''}
                </span>
            </div>
        </div>
    );
};
